package org.example.study.url;

import org.junit.Test;

import javax.net.ssl.HttpsURLConnection;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class TestURL {

    @Test
    public void testURL() throws MalformedURLException {

        // public String getProtocol() 获取该URL的协议名
        // public String getHost() 获取该URL的主机名
        // public String getPort() 获取该URL的端口号
        // public String getPath() 获取该URL的文件路径
        // public String getFile() 获取该URL的文件名
        // public String getQuery() 获取该URL的查询名

        URL url = new URL("https://i2.hdslb.com/bfs/archive/8a96eeb1e9068f5a3eae132ea6075622170fc981.jpg@336w_190h_1c.webp");

        System.out.println(url.getProtocol());
        System.out.println(url.getHost());
        System.out.println(url.getPort());
        System.out.println(url.getPath());
        System.out.println(url.getFile());
        System.out.println(url.getQuery());
    }

    @Test
    public void downloadFile() throws IOException {
        // 实现数据下载
        URL url = new URL("https://i2.hdslb.com/bfs/archive/8a96eeb1e9068f5a3eae132ea6075622170fc981.jpg@336w_190h_1c.webp");

        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.connect();
        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fileOutputStream = new FileOutputStream("03.webp");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, len);
        }

        fileOutputStream.close();
        inputStream.close();
        urlConnection.disconnect();
    }
}
